'use strict';
/**
 *
 *DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
  `user_id` double NOT NULL AUTO_INCREMENT,
  `user_name` varchar(150) DEFAULT NULL,
  `remark` varchar(600) DEFAULT NULL,
  `origin` varchar(60) DEFAULT NULL,
  `app_id` varchar(100) DEFAULT NULL,
  `insert_time` datetime DEFAULT NULL,
  `edit_time` datetime(3) DEFAULT NULL,
  `last_login_time` datetime(3) DEFAULT CURRENT_TIMESTAMP(3),
  `status` varchar(20) DEFAULT NULL,
  `last_password_reset_date` datetime(3) DEFAULT NULL,
  PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=193 DEFAULT CHARSET=utf8;
)
 *
 * 只有在service层才能调用model层数据库接口，不允许在controller层调用
 * 注意事项：
 * 1. 调用model层时，首字母必须大写，否则找不到
 * 2. 在调用数据时，不建议使用 Sequelize 自带的创建时间和修改时间，这样会产生东8区的时差问题
 * 3. 在写一些比较复杂的sql语句时，如果对于 Sequelize 不熟的话，可以选择自定义 sql ，用 app.model.query(sql)
 *
 */
module.exports = app => {
	const Sequelize = app.Sequelize;
	//const { STRING, INTEGER, DATE,  } = app.Sequelize;

	const user = app.model.define('user', {
		id: {
			type: Sequelize.INTEGER,
			primaryKey: true,
			autoIncrement: true,
		},
		url: {
			type: Sequelize.STRING,
		},
		param: {
			type: Sequelize.STRING,
		},
		image: {
			type: Sequelize.STRING,
		},
		pdf: {
			type: Sequelize.STRING,
		},
		errorMsg: {
			type: Sequelize.STRING,
		},
		callback: {
			type: Sequelize.STRING,
		},
		created_at: {
			type: Sequelize.DATE,
		},
		updated_at: {
			type: Sequelize.DATE,
		},
		state:{
			type: Sequelize.STRING,
		},
	}, {
		tableName: 'user',
		timestamps: false,
		underscoredAll: true
	});



	/**
	 * 创建一条记录
	 */

	user.insertUser = async (param)=> {
		return param
	};

	/**
	 * 查询一条记录
	 */

	user.findOneUser = function() {
		return new Promise((resolve, reject) => {
			let randint = parseInt(Math.random()*1);
			let sql = `SELECT id,state,param,url,callback FROM tasks where state = 0 limit `+randint+`, 1`;
			app.model.query(sql).spread((results, metadata) => {
				resolve(results);
			}).catch(err => {
				reject(err);
			});
		});
	};

	user.verificationData = function(id) {
		//let time = curentTime();
		return new Promise((resolve, reject) => {
			let sql = `UPDATE tasks SET state = 1 WHERE state = 0 AND id = ${id}`;

			app.model.query(sql).spread((results, metadata) => {
				resolve(results);
			}).catch(err => {
				reject(err);
			});
		});
	};

	user.updateById = function(attr, id) {
		let uData = Object.assign({}, attr);
		return new Promise((resolve, reject) => {
			this.update(uData, {
				where: {
					id
				}
			}).then(data => {
				resolve(data);
			}).catch(err => {
				reject(err);
			});
		});
	};

	return user;
};
